﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace WikiBugtracker.WikiCommon
{
    class RootManager
    {
        private string root_folder_ = String.Empty;
        private string root_file_ = "root.xml";

        private string projects_folder_ = "Projects\\";
        private string project_file_ = "Project.xml";

        public RootManager(String root_folder)
        {
            root_folder_ = root_folder;
        }

        private String RootFile()
        {
            return root_folder_ + root_file_;
        }

        private String ProjectPath(String project_name)
        {
            return root_folder_ + projects_folder_ + project_name + "\\";
        }

        private String ProjectFilePath(String project_name)
        {
            return ProjectPath(project_name) + project_file_;
        }

        public Root LoadRoot()
        {
            Root result = new Root();

            return result.Deserialize(RootFile(), ref result);
        }

        public void WriteRoot(Root root)
        {
            root.Serialize(RootFile());
        }

        public void RenameProject(String old_project_name, String new_project_name)
        {
            System.IO.Directory.Move(ProjectPath(old_project_name), ProjectPath(new_project_name));
        }

        public Project LoadProject(String project_name)
        {
            Project result = new Project();

            return result.Deserialize(ProjectFilePath(project_name), ref result);
        }

        public void WriteProject(Project project)
        {
            System.IO.Directory.CreateDirectory(ProjectPath(project.Name));
            project.Serialize(ProjectFilePath(project.Name));
        }
    }

    class Root : ISecureSerializable
    {
        public DateTime TimeStamp { get; set; }
        public Int64 ProjectID { get; set; }
        public List<String> Projects { get; set; }
        public List<String> Users { get; set; }
        public Int64 BugCount { get; set; }

        public Root()
        {
            ProjectID = 0;
        }

        public Int64 GetNextProjectID()
        {
            return ++ProjectID;
        }

        public Int64 AddProject(String project_name)
        {
            Projects.Add(project_name);

            return GetNextProjectID();
        }
    }
}
